from menu_manager import MenuManager
from file_manager import FileManager
from student import Student


class StudentManager:
    def __init__(self):
        self.menu_manager = MenuManager()
        self.file_manager = FileManager('data.txt')
        self.student_list = self.file_manager.read()

    def run(self):
        while True:
            self.menu_manager.print_menu()
            option = input('请选择菜单：')

            try:
                if option == '1':
                    self.add()

                if option == '2':
                    self.delete()

                if option == '3':
                    self.update()

                if option == '4':
                    self.query_by_id()

                if option == '5':
                    self.query_all()

                if option == '6':
                    self.sort()

                if option == '0':
                    self.quit()
                    break
            except Exception as e:
                print(e)

    def quit(self):
        self.file_manager.write_list(self.student_list)
        print('程序运行结束')

    def is_exists(self, id):
        exists = False

        for item in self.student_list:
            if item.id == id:
                exists = True

        return exists

    def add(self):

        # 对输入信息进行校验
        stu_id = input('请输入学号：')

        if self.is_exists(stu_id):
            print('id已存在！')
            return

        student = Student.init_from_input()
        student.id = stu_id

        self.student_list.append(student)

    def update(self):
        stu_id = input('请输入待更新学生学号：')
        if not self.is_exists(stu_id):
            print('id不存在！')
            return

        # remove stu from list
        for item in self.student_list:
            if item.id == stu_id:
                self.student_list.remove(item)

        stu = Student.init_from_input()
        stu.id = stu_id

        self.student_list.append(stu)

    def delete(self):
        student_id = input(f'请输入待删除学生学号: ')
        if not self.is_exists(student_id):
            print('id不存在！')
            return

        for item in self.student_list:
            if item.id == student_id:
                self.student_list.remove(item)


    def query_all(self):
        self.menu_manager.print_student_list(self.student_list)

    def sort(self):
        self.student_list.sort(key=lambda x: x.sum_score)

    def query_by_id(self):
        query_id = input('请输入id: ')

        if not self.is_exists(query_id):
            print('id不存在！')
            return

        for item in self.student_list:
            if item.id == query_id:
                self.menu_manager.print_student_list([item])

    def query_by_name(self):
        pass


if __name__ == '__main__':
    student_manager = StudentManager()
    student_manager.run()
